import baseData from "./components/base-data";
import transferData from "./components/transfer-data";
import propertyOwnership from "./components/property-ownership";
import {
    save,
    get,
    edit,
    getLandInfo,
	updateWarning
} from "@/views/property-info-sys/property-manage/api/room";
import BaseLoad from "@/assets/vue-mixin/BaseLoad";
import { mapGetters } from "vuex";

export default {
    name: "resource-manage-edit",
    mixins: [BaseLoad],
    components: { baseData, propertyOwnership, transferData },
    created() {
        this.landUses = this.getDict("land_uses");
        this.streets = this.getDict("streets");
        this.communityNames = this.getDict("community_names");
        let param = this.$route.query.id;
        this.projectId = this.$route.query.projectId;
        if (param) {
            this.loadAction("数据加载中");
            this.id = param;
            this.isAdd = false;
            //初始化数据
            get(this.id)
                .then(rep => {
                    let repData = rep.data.data;
                    this.roomInfo = repData.roomInfo;
                    this.oldPropertyName = repData.roomInfo.propertyName
                    this.propertyInfo = repData.propertyInfo;
                    this.propertyCard = repData.propertyCard;
                    this.$refs.baseData.updateInit(this.roomInfo);
                    this.$refs.belong.initOwner(
                        this.propertyInfo,
                        this.propertyCard,
                        this.roomInfo.propertyOwnership
                    );
                    this.$refs.transfer.initTransfer(this.roomInfo);
                    //
                    this.$refs.propertyFiles.getFiles(this.id);
                    this.loadClose();
                })
                .catch(e => {
                    this.loadClose();
                });
            this.handleGetLandInfo(1);
        }
    },
    data() {
        return {
            id: "",
            projectId: "",
            isAdd: true,
            uploadFileList: [],
					  oldPropertyName: '',
            modelType: "property",
            //文件上传失败标识，true失败 false成功
            uploadError: false,
            tableData: [],
            roomInfo: {},
            propertyInfo: {},
            propertyCard: {},
            landInfo: {
                address: "",
                addressInfo: "",
                landContractNum: "",
                landId: "",
                landUse: "",
                parcelArea: "",
                parcelNum: "",
                remarks: ""
            },
            landUses: [],
            streets: [],
            communityNames: []
        };
    },
    methods: {
        submitForm() {
            //  创建各个表单的验证信息

            //    基础信息
            const baseForm = new Promise((resolve, reject) => {
                this.$refs["baseData"].$refs["baseForm"].validate(valid => {
                    if (valid) resolve();
                });
            });
            //地址选择器
            /*const citySelectForm = new Promise((resolve, reject) => {
                this.$refs['baseData'].$refs['citySelectForm'].$refs['cityForm'].validate((valid) => {
                    if (valid) resolve();
                })
            })*/

            //权属信息
            const belongForm = new Promise((resolve, reject) => {
                let borrowForm = this.$refs["belong"].$refs["borrowForm"];
                if (borrowForm) {
                    borrowForm.validate(valid => {
                        if (valid) resolve();
                    });
                } else {
                    resolve();
                }
            });
            // Promise.all([baseForm, citySelectForm, belongForm]).then(() => {
            Promise.all([baseForm, belongForm]).then(() => {

							//    拿到基本信息数据
							let baseFormData = this.$refs["baseData"].baseForm;
							//判断物业名称是否发生变更，如果发生变更， 则需要给出提醒
							if(!this.isAdd && this.oldPropertyName != baseFormData.propertyName){
								this.loadAction("正在验证");
								updateWarning({roomId : this.id}).then(rep => {
									if(rep.data.data.code != '0'){
										this.$confirm(rep.data.data.msg, '提示', {
											confirmButtonText: '确定',
											cancelButtonText: '取消',
											type: 'warning'
										}).then(() => {
											this.loadClose();
												//文件上传
												if (this.uploadFileList.length > 0) {
													this.$refs.propertyFiles.submit(this.modelType, this.id);
												} else {
													this.sendFormData();
												}
										}).catch(() => {
											this.loadClose();
											this.$message({
												type: 'info',
												message: '已取消'
											});
										});
									}else{
										this.loadClose();
										this.sendFormData();
									}
								})
							}else{
								this.sendFormData();
							}

            });
        },
        sendFormData() {
            //加入VR
            if (this.$refs["baseData"].baseForm.vrUrl) {
                this.$refs["baseData"].baseForm.isVr = "1";
            } else {
                this.$refs["baseData"].baseForm.isVr = "0";
            }
            //    拿到基本信息数据
            let baseFormData = this.$refs["baseData"].baseForm;

            //移交信息
            let transferFormData = this.$refs["transfer"].transferForm;

            this.loadAction("数据保存中");
            baseFormData.areaCode =
                baseFormData.cityCode + "-" + baseFormData.countyCode;
            baseFormData.areaName =
                this.getCardTypeValue(
                    baseFormData.cityCode,
                    this.cityAssembly
                ) +
                this.getCardTypeValue(
                    baseFormData.countyCode,
                    this.districtCollection
                ) +
                this.getCardTypeValue(baseFormData.roomStreet, this.streets) +
                this.getCardTypeValue(
                    baseFormData.communityName,
                    this.communityNames
                );
            if (this.isAdd) {
                //权属类型
                let propertyOwnershipData = this.$refs["belong"]
                    .propertyOwnership;

                //除政府产权以外的信息
                let borrowForm = this.$refs["belong"].borrowForm;

                save({
                    roomInfo: Object.assign(
                        {
                            propertyOwnership: propertyOwnershipData,
                            roomId: this.id
                        },
                        baseFormData,
                        transferFormData
                    ),
                    propertyInfo: borrowForm
                })
                    .then(rep => {
                        this.loadClose();
                        this.$message({
                            message: "保存成功",
                            type: "success"
                        });
                        this.closeNowRouter();
                    })
                    .catch(e => {
                        this.loadClose();
                        this.err("提交失败");
                    });
            } else {
                //除政府产权以外的信息
                let borrowForm = this.$refs["belong"].borrowForm;
                edit({
                    roomInfo: Object.assign(baseFormData, transferFormData),
                    propertyInfo: borrowForm
                })
                    .then(rep => {
                        this.loadClose();
                        this.$message({
                            message: "修改成功",
                            type: "success"
                        });
                        this.closeNowRouter();
                    })
                    .catch(e => {
                        this.loadClose();
                        this.err("修改失败");
                    });
            }
        },
        closeNowRouter() {
            //关闭当前新增页，暂时没找到好办法
            this.$store.commit("delHistoryRoute", this.$route.fullPath);
            //跳转
            this.$router.push("/property-info-sys/property-manage");
        },
        onSuccess(response, file, fileList) {
            this.id = response.data;
            this.sendFormData();
        },
        onError(err, file, fileList) {
            this.uploadError = true;
        },
        // hxf-1010-根据id获取土地信息
        handleGetLandInfo(type) {
            getLandInfo(type, this.projectId).then(res => {
                if (res.data.code === 0 && res.data.data !== null) {
                    this.landInfo = res.data.data;
                }
            });
        },
        // hxf-1010-回显时对应value显示label
        getCardTypeValue(num, sum) {
            let arr = sum.filter(e => e.value === num);
            if (arr.length > 0) {
                return arr[0].label;
            } else {
                return num;
            }
        },
        // 物业权属调用
        handleControlOwnership(val) {
            this.$refs["belong"].selectOwner(val.val);
        }
    },
    computed: {
        ...mapGetters({
            cityAssembly: "getCityAssembly",
            districtCollection: "getDistrictCollection"
        })
    }
};
